package com.gxpt.app.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnItemLongClickListener;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.recyclerview.ProgressStyle;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.gxpt.app.AppUtils;
import com.gxpt.app.BaseFragment;
import com.gxpt.app.Constant;
import com.gxpt.app.MessageEvent;
import com.gxpt.app.R;
import com.gxpt.app.adapter.shopping_list_Adapter;
import com.gxpt.app.bean.getcartinfo_bean;
import com.gxpt.app.bean.normal;
import com.gxpt.app.view.Activity_shopping_confirm;
import com.utils.T;
import com.utils.logger.Logger;
import com.utils.okhttputils.HttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * Created by dufeng on 2017/9/8.
 */

@ContentView(R.layout.fragment_shopping)
public class Fragment_shopping extends BaseFragment {

    Context context;
    /**服务器端一共多少条数据*/
    private static final int TOTAL_COUNTER = 10000;//如果服务器没有返回总数据或者总页数，这里设置为最大值比如10000，什么时候没有数据了根据接口返回判断

    /**每一页展示多少条数据*/
    private static final int REQUEST_COUNT = 20;

    /**已经获取到多少条数据了*/
    private static int mCurrentCounter = 0;

    private shopping_list_Adapter mDataAdapter = null;


    private LRecyclerViewAdapter mLRecyclerViewAdapter = null;

    ///////////////////
    int page_num  = 1;
    int page_size = 20;



    @ViewInject(R.id.null_car)
    LinearLayout null_car;

    @ViewInject(R.id.view_bar)
    LinearLayout view_bar;

    @ViewInject(R.id.mLRecyclerView)
    LRecyclerView mLRecyclerView;

    @ViewInject(R.id.cb_all)
    CheckBox cb_all;

    @ViewInject(R.id.txt_heji)
    TextView txt_heji;

    @ViewInject(R.id.txt_goods_count)
    TextView txt_goods_count;

    @ViewInject(R.id.toShow)
    TextView toShow;

    private View footerView;

    String action  = "";
    String cart_id = "";

    double price_all = 0;
    int    count_all = 0;

    JSONArray jy = new JSONArray();



    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(hidden == false){
            AppUtils.isShowAreaSel(context);
        }
    }


    @Override
    public void onAttach(Context context) {
        this.context = context;
        super.onAttach(context);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = x.view().inject(this, inflater, container);
        initViews();
        initData();
        return rootView;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MessageEvent messageEvent){

        switch (messageEvent.getMessageType()){
            case Constant.ACTION_carinfo_add:
                String tmp = messageEvent.getMessage();
                Logger.i("+ = "+tmp);
                do_add(tmp);
                break;
            case Constant.ACTION_carinfo_sub:
                String tmp2 = messageEvent.getMessage();
                Logger.i("- = "+tmp2);
                do_sub(tmp2);
                break;
        }

        if(messageEvent.getMessageType()==Constant.ACTION_to_shopping_add || messageEvent.getMessageType()==Constant.ACTION_to_shopping_reduce){

            cart_id = messageEvent.getData_str();
            action  = messageEvent.getData_ids();

            mDataAdapter.clear();
            mLRecyclerViewAdapter.notifyDataSetChanged();//fix bug:crapped or attached views may not be recycled. isScrap:false isAttached:true
            mCurrentCounter = 0;

            toNet_updatecart();
        }else if(messageEvent.getMessageType()==Constant.ACTION_to_shopping_allCheck){
            if(messageEvent.getIs()){
                cb_all.setChecked(true);
            }else{
                cb_all.setChecked(false);
            }
        }else if(messageEvent.getMessageType()==Constant.ACTION_to_shopping_refresh){
            mDataAdapter.clear();
            mLRecyclerViewAdapter.notifyDataSetChanged();//fix bug:crapped or attached views may not be recycled. isScrap:false isAttached:true
            mCurrentCounter = 0;
            mCurrentCounter = 0;
            do_Refresh();
        }
    }

    private void do_add(String tmpStr){
        boolean isDO = true;
        Logger.i(" 加jy = "+jy.toString());
        for(int i=0;i<jy.length();i++){
            try {

                JsonParser parser1 = new JsonParser();
                JsonObject jsontmp = (JsonObject) parser1.parse(tmpStr);  //把str1解析成json对象

                JsonParser parser2 = new JsonParser();
                JsonObject jsontmp_jy = (JsonObject) parser2.parse(jy.get(i).toString());  //把str1解析成json对象

                if(jsontmp_jy.equals(jsontmp)){
                    isDO = false;
                    break;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        if(isDO){
            try {
                JSONObject jsoncar = new JSONObject(tmpStr);
                jy.put(jsoncar);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Logger.i("加jy2 = "+jy.toString());
        count_goods();
    }

    private void do_sub(String tmpStr){
        boolean isDO2 = false;
        int index = 0;
        Logger.i("减jy = "+jy.toString());
        for(int i=0;i<jy.length();i++){
            try {

                JsonParser parser1 = new JsonParser();
                JsonObject jsontmp = (JsonObject) parser1.parse(tmpStr);  //把str1解析成json对象

                JsonParser parser2 = new JsonParser();
                JsonObject jsontmp_jy = (JsonObject) parser2.parse(jy.get(i).toString());  //把str1解析成json对象

                if(jsontmp_jy.equals(jsontmp)){
                    index = i;
                    isDO2 = true;
                    break;
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        Logger.i("isDO2 = "+isDO2);

        if(isDO2){
            try {
                jy.remove(index);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Logger.i("减jy2 = "+jy.toString());
        count_goods();
    }


    private void initViews(){

        cb_all.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                        for (int i = 0; i < mLRecyclerView.getChildCount(); i++) {
                            View view = mLRecyclerView.getChildAt(i);
                            if (view instanceof LinearLayout){
                                LinearLayout lt = (LinearLayout)mLRecyclerView.getChildAt(i);
                                if(lt.getChildCount() == 3){
                                    for (int m = 0; m < 3; m++) {

                                        if(lt.getChildAt(m).getId() == R.id.shop_layout){
                                            CheckBox cb_shop = (CheckBox)lt.getChildAt(m).findViewById(R.id.cb_shop);
                                            cb_shop.setChecked(true);
                                            break;
                                        }

                                    }
                                }
                            }
                        }

                }else{
                    for (int i = 0; i < mLRecyclerView.getChildCount(); i++) {
                        View view = mLRecyclerView.getChildAt(i);
                        if (view instanceof LinearLayout){
                            LinearLayout lt = (LinearLayout)mLRecyclerView.getChildAt(i);
                            if(lt.getChildCount() == 3){
                                for (int m = 0; m < 3; m++) {

                                    if(lt.getChildAt(m).getId() == R.id.shop_layout){
                                        CheckBox cb_shop = (CheckBox)lt.getChildAt(m).findViewById(R.id.cb_shop);
                                        cb_shop.setChecked(false);
                                        break;
                                    }

                                }
                            }
                        }
                    }
                }
            }
        });



        initFooterView();


        mDataAdapter = new shopping_list_Adapter(context);
        mLRecyclerViewAdapter = new LRecyclerViewAdapter(mDataAdapter);
        mLRecyclerView.setAdapter(mLRecyclerViewAdapter);

//        DividerDecoration divider = new DividerDecoration.Builder(this)
//                .setHeight(R.dimen.default_divider_height)
//                .setPadding(R.dimen.default_divider_padding)
//                .setColorResource(R.color.split)
//                .build();

        mLRecyclerView.setLayoutManager(new LinearLayoutManager(context));

        mLRecyclerView.setRefreshProgressStyle(ProgressStyle.LineSpinFadeLoader);
        mLRecyclerView.setArrowImageView(R.drawable.ic_pulltorefresh_arrow);
        mLRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallSpinFadeLoader);

        //add a HeaderView
//        final View header = LayoutInflater.from(this).inflate(R.layout.sample_header,(ViewGroup)findViewById(android.R.id.content), false);
//        mLRecyclerViewAdapter.addHeaderView(footerView);


        mLRecyclerView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                mDataAdapter.clear();
                mLRecyclerViewAdapter.notifyDataSetChanged();//fix bug:crapped or attached views may not be recycled. isScrap:false isAttached:true
                mCurrentCounter = 0;
                do_Refresh();
            }
        });

        //是否禁用自动加载更多功能,false为禁用, 默认开启自动加载更多功能
        mLRecyclerView.setLoadMoreEnabled(false);

        mLRecyclerView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                do_LoadMore();
//                if (mCurrentCounter < TOTAL_COUNTER) {
//                    // loading more
//                    requestData();
//                } else {
//                    //the end
//                    mLRecyclerView.setNoMore(true);
//                }
            }
        });

        //设置头部加载颜色
        mLRecyclerView.setHeaderViewColor(R.color.red, R.color.red ,android.R.color.white);
        //设置底部加载颜色
        mLRecyclerView.setFooterViewColor(R.color.red, R.color.red ,android.R.color.white);
        //设置底部加载文字提示
        mLRecyclerView.setFooterViewHint("拼命加载中","已经全部为你呈现了","网络不给力啊，点击再试一次吧");

        mLRecyclerView.refresh();

        mLRecyclerViewAdapter.addFooterView(footerView);
        mLRecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (mDataAdapter.getDataList().size() > position) {
                    getcartinfo_bean.getcartinfo item = mDataAdapter.getDataList().get(position);


                }

            }

        });

        mLRecyclerViewAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public void onItemLongClick(View view, int position) {
//                ItemModel item = mDataAdapter.getDataList().get(position);
//                T.show(getApplicationContext(), "onItemLongClick - " + item.title,1);
            }
        });
    }
    private void do_Refresh(){
        page_num = 1;
        init_views();
        toNet_getcartinfo();
    }

    private void do_LoadMore(){
//        page_num += 1;
//        toNet_getcartinfo();
    }

    private void initData(){

    }

    private void notifyDataSetChanged() {
        mLRecyclerViewAdapter.notifyDataSetChanged();
    }

    private void addItems(ArrayList<getcartinfo_bean.getcartinfo> list) {

        mDataAdapter.addAll(list);
        mCurrentCounter += list.size();

        //全部数据 list
    }


    private void count_goods(){
        double price_all = 0;
        int    count_all = 0;

        for(int i=0;i<jy.length();i++){
            try{
                count_all += Integer.parseInt(""+((JSONObject)jy.get(i)).get("goods_num"));
                price_all += Double.parseDouble(""+((JSONObject)jy.get(i)).get("tmp_sell_price")) * Integer.parseInt(""+((JSONObject)jy.get(i)).get("goods_num"));
            }catch (Exception e){

            }

        }

        txt_heji.setText(context.getString(R.string.txt_azongjia, (""+price_all)));
        txt_goods_count.setText(context.getString(R.string.txt_jijian, count_all));

    };

    private void count_goods(ArrayList<getcartinfo_bean.getcartinfo> list){
        double price_all = 0;
        int    count_all = 0;
        try {
            for (int i = 0, len = jy.length(); i < len; i++) {

                jy.remove(i);
            }
        }catch (Exception e){

        }

        for(int a=0;a<list.size();a++) {

            List<getcartinfo_bean.getcartinfo.good> goods = list.get(a).goods;
            for (int b = 0; b < goods.size(); b++) {

                try {
                    JSONObject jsoncar = new JSONObject();
                    jsoncar.put("shop_id", "" + goods.get(a).shop_id);
                    jsoncar.put("cart_id", "" + goods.get(b).cart_id);
                    jsoncar.put("goods_id", "" + goods.get(b).goods_id);
                    jsoncar.put("sku_id", "" + goods.get(b).sku_id);
                    jsoncar.put("goods_num", "" + goods.get(b).goods_num);
                    jsoncar.put("tmp_sell_price", "" + goods.get(b).sell_price);
                    jy.put(jsoncar);

                    count_all += Integer.parseInt(goods.get(b).goods_num);
                    price_all += Double.parseDouble(goods.get(b).sell_price) * Integer.parseInt(goods.get(b).goods_num);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }

        txt_heji.setText(context.getString(R.string.txt_azongjia, (""+price_all)));
        txt_goods_count.setText(context.getString(R.string.txt_jijian, count_all));
    }

    private void init_views(){
        double price_all = 0;
        int    count_all = 0;
        txt_heji.setText(context.getString(R.string.txt_azongjia, (""+price_all)));
        txt_goods_count.setText(context.getString(R.string.txt_jijian, count_all));
    }


    private void initFooterView(){
        footerView = LayoutInflater.from(context).inflate(R.layout.common_home_menu_hidden,null, false);
        footerView.setLayoutParams(new LRecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT));
;
    }


    @Event(value={R.id.toShow})
    private void getEvent(View view){
        switch(view.getId()){

            case R.id.toShow:
                Logger.i("jy2 = "+jy.toString());

                Intent gotAddneed = new Intent();
                gotAddneed.putExtra("DATA",jy.toString());
                gotAddneed.setClass(context, Activity_shopping_confirm.class);
                startActivity(gotAddneed);
                break;
        }
    }



    /////NET

    private void toNet_getcartinfo(){
//        hud.show();
        JSONObject jsonBody=new JSONObject();
        try {
            jsonBody.put("device_number",         AppUtils.get_device_id(context));
            jsonBody.put("device_type",           Constant.device_type);
            jsonBody.put("token",                 AppUtils.get_token(context));
            jsonBody.put("pageName",             "shopcart");
            jsonBody.put("serviceName",          "getcartinfo");

            jsonBody.put("member_id",                AppUtils.get_user_id(context));//二级地区ID
        } catch (JSONException e) {
            e.printStackTrace();
        }
//        Logger.i(jsonBody.toString()+"  ["+Constant.URL_getcartinfo+"]");
        HttpUtils.http_post_string(Constant.URL_getcartinfo,jsonBody.toString(),do_getcartinfo);
    }

    //////NET DO

    StringCallback do_getcartinfo = new StringCallback(){


        @Override
        public void onError(Call call, Exception e, int i) {
            Logger.e(e.getMessage());
            mLRecyclerView.refreshComplete(REQUEST_COUNT);
        }

        @Override
        public void onResponse(String s, int i) {
            mLRecyclerView.refreshComplete(REQUEST_COUNT);
//            if(hud.isShowing()){
//                hud.dismiss();
//            }
//            Logger.e(s);
            try{
                getcartinfo_bean data = new Gson().fromJson(s, getcartinfo_bean.class);
                if(data.state !=1 ){
                    T.show(context,data.msg,0);
                }else{
                    if(data.data != null){
                        if(data.data.size()>0){
                            addItems((ArrayList)data.data);
                            notifyDataSetChanged();

                            count_goods((ArrayList)data.data);

                            //


                            null_car.setVisibility(View.GONE);
                            view_bar.setVisibility(View.VISIBLE);
                        }else{
                            page_num -= 1;

                            //
                            null_car.setVisibility(View.VISIBLE);
                            view_bar.setVisibility(View.GONE);
                        }
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
                T.show(context,getResources().getString(R.string.alert_again),0);
            }
        }
    };


    private void toNet_updatecart(){//+ -
//        hud.show();
        JSONObject jsonBody=new JSONObject();
        try {
            jsonBody.put("device_number",         AppUtils.get_device_id(context));
            jsonBody.put("device_type",           Constant.device_type);
            jsonBody.put("token",                 AppUtils.get_token(context));
            jsonBody.put("pageName",             "shopcart");
            jsonBody.put("serviceName",          "updatecart");

            jsonBody.put("member_id",             AppUtils.get_user_id(context));
            jsonBody.put("cart_id",               cart_id);
            jsonBody.put("action",                action);
        } catch (JSONException e) {
            e.printStackTrace();
        }
//        Logger.i(jsonBody.toString()+"  ["+Constant.URL_updatecart+"]");
        HttpUtils.http_post_string(Constant.URL_updatecart,jsonBody.toString(),do_updatecart);
    }

    StringCallback do_updatecart = new StringCallback(){


        @Override
        public void onError(Call call, Exception e, int i) {
//            if(hud.isShowing()){
//                hud.dismiss();
//            }
            Logger.e(e.getMessage());
            mLRecyclerView.refreshComplete(REQUEST_COUNT);
        }

        @Override
        public void onResponse(String s, int i) {
            mLRecyclerView.refreshComplete(REQUEST_COUNT);
//            if(hud.isShowing()){
//                hud.dismiss();
//            }
//            Logger.e(s);
            try{
                normal data = new Gson().fromJson(s, normal.class);
                if(data.state !=1 ){
                    T.show(context,data.msg,0);
                }else{
                    mLRecyclerView.refresh();
                }
            }catch (Exception e){
                e.printStackTrace();
                T.show(context,getResources().getString(R.string.alert_again),0);
            }
        }
    };
}
